package cn.yunyichina.provider.guide.service.impl;

import java.util.Calendar;
import java.util.List;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import com.alibaba.dubbo.common.utils.CollectionUtils;

import cn.yunyichina.provider.framework.dubbo.service.HisifaceService;
import cn.yunyichina.provider.guide.GuideConstants;
import cn.yunyichina.provider.guide.dao.InstanceDao;
import cn.yunyichina.provider.guide.dao.InstanceNodeDao;
import cn.yunyichina.provider.guide.dao.InstanceRelationDao;
import cn.yunyichina.provider.guide.dao.TemplateDao;
import cn.yunyichina.provider.guide.entity.Instance;
import cn.yunyichina.provider.guide.entity.InstanceNode;
import cn.yunyichina.provider.iface.entity.ErrorCodeDefine;
import cn.yunyichina.provider.iface.entity.common.ResCommon;
import cn.yunyichina.provider.iface.entity.hisiface.leads.ClinicAddressInfoVo;
import cn.yunyichina.provider.iface.entity.hisiface.leads.ClinicAddressInfoVoResponse;
import cn.yunyichina.utils.convert.JsonUtils;

/**
 * 导医,定时更新挂号状态
 * @author adriftor
 *
 */
@Service("guidesyncclinicaddressinfoServiceImpl")
public class GuideSyncClinicAddressInfoServiceImpl  {
	
	private static final Logger logger = LoggerFactory.getLogger(GuideSyncClinicAddressInfoServiceImpl.class);
	
	
	
	@Resource
	private InstanceDao instanceDao;
	
	@Resource
	private TemplateDao templateDao;
	
	@Resource
	private InstanceNodeDao instanceNodeDao;
	
	@Resource
	private InstanceRelationDao instanceRelationDao;
	
	@Resource
	private GuideTemplateServiceImpl guideTemplateService;
	
	@Resource
	private GuideInstanceServiceImpl guideInstanceService;
	
	
	private static Boolean isRunning = false;
	
	@Resource
	private GuideSyncStopServiceImpl guideSyncEndService;

	
	/**
	 * 订单生成的节点，调用HIS以便货到后续处理节点
	 * @param strJson
	 * @param instanceId
	 */
	public void doGuideSync() {
		
		if (isRunning) {
			logger.info("定时获取缴费后路由信息正在运行,禁止重入");
			return;
		}
		
		isRunning = true;
		
		try {
			
			logger.info("sync-address:start");
			Calendar c = Calendar.getInstance();
			c.add(Calendar.HOUR_OF_DAY, -24);

			List<InstanceNode> listInstanceNode = instanceNodeDao.selectClinicRunningInstanceNode(GuideConstants.YYYYMMDDHHMMSS.format(c.getTime()));
			logger.info("listInstanceNode-size="+listInstanceNode.size());
			
			for (InstanceNode thisInstanceNode : listInstanceNode) {
				
				try {
					guideInstanceService.refleshGuideInstanceAddressInfo(thisInstanceNode.getOrderNo());
						
				} catch (Exception e) {
					logger.error("根据新路由信息，流程处理异常："+JsonUtils.toJsonString(thisInstanceNode),e);
				}
				
			}//for
					


			logger.info("sync-address--ok");
		}
		catch (Exception ex) {
			logger.error(ErrorCodeDefine.GUIDE_COMMON,"定时获取缴费后路由信息异常",ex);
		}
		finally {
			isRunning = false;
		}
		
	}
	

}
